<template>
  <div :class="$style.wrap">
    <ContentWrap>
      <Input ref="search" @query="queryHandle" />
      <div class="button-container" style="padding-top:0">
        <ExportPane :data-source="selectedList" :other-filters="otherFilters" :table-config="tableConfig" :query-data-fun="queryDataFun" filename="号码资源管理">导出</ExportPane>
        <DialogUpload
          ref="export"
          :show-file-num="false"
          text="导入"
          title="导入"
          down-temp-url="/call-center/api/v1/prefixNumberInfo/download"
          file-name="号码资源管理导入模板.xlsx"
          :exist-file-list="existFileList"
          :click-down="false"
          :on-change="onChangeHandle"
          :on-remove="removeFileHandle"
          :on-exceed="onExceed"
          :limit="1"
          @confirm="onConfirmHandle"
        ></DialogUpload>
        <Button type="primary" @click="visibleAdd=true">新增</Button>
        <Button type="primary" @click="editHandle">修改</Button>
        <Button type="danger" @click="removeHandle">删除</Button>
      </div>
      <table-box ref="table" no-request :other-filters="otherFilters" :selected-arry.sync="selectedArry" :table-config="tableConfig" @selection-change="selectionChange">
        <el-table-column slot="before" type="selection" width="50" />
      </table-box>
    </ContentWrap>
    <el-dialog :visible.sync="visibleAdd" title="新增" :close-on-click-modal="false" destroy-on-close>
      <Input v-if="visibleAdd" :column="1" :is-query="false" @close="visibleAdd=false" @refresh="refreshTable()" />
    </el-dialog>
    <el-dialog :visible.sync="visibleEdit" title="编辑" :close-on-click-modal="false" destroy-on-close>
      <Input v-if="visibleEdit" :column="1" :is-query="false" :row="selectedList[0]" @close="visibleEdit=false" @refresh="refreshTable('onPage')" />
    </el-dialog>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import Input from './components/input'
import { filtersRaw } from '@/utils'
import { deleteBatch, numberImport } from '@/api/prefixNumberInfo'
import DialogUpload from '@/components/Upload/DialogUpload'
import ExportPane from '@/components/ExportPane'
export default {
  name: 'PhoneManage',
  components: {
    ContentWrap,
    Input,
    DialogUpload,
    ExportPane
  },
  data() {
    return {
      // 导入
      existFileList: [], //
      fileList: [], // 已导入的文件
      tableConfig: {
        interfacePath: '/call-center/api/v1/prefixNumberInfo/page',
        pageFlag: true,
        hideFuncBar: true,
        sort: 'prefixNumber',
        order: 'asc',
        // 表格字段动态配置
        setting: [
          {
            label: '序号',
            formatData: v => v.keyIndex + 1
          },
          {
            prop: 'prefixNumber',
            label: '前缀'
          },
          {
            prop: 'phoneNumber',
            label: '号码'
          },
          {
            prop: 'telecomOperator',
            label: '运营商',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'call-center',
              dictTypeCode: 'TELECOM_OPERATOR'
            }
          },
          {
            prop: 'skillName',
            label: '使用技能组'
          },
          {
            prop: 'createBy',
            label: '创建人'
          },
          {
            prop: 'createTime',
            label: '创建时间'
          }
        ]
      },
      selectedArry: [], // 选中项
      selectedList: [], // 选中项
      otherFilters: [],
      visibleAdd: false,
      visibleEdit: false
    }
  },
  computed: {
    hasSelected() {
      return this.selectedList.length > 0
    }
  },
  watch: {
    selectedArry() {
      // this.$nextTick(() => {
      //   this.selectedArry = []
      // })
    }
  },
  methods: {
    queryDataFun(type) {
      const data = this.$refs.search.clickHandle(type)
      return this.queryHandle(data, type)
    },
    queryHandle(data, type) {
      const otherFilters = []
      if (data !== undefined) {
        for (const key of Object.keys(data)) {
          if (data[key] === '') {
            continue
          }
          if (key === 'skillNo') {
            otherFilters.push(filtersRaw(key, `,${data[key]},`, 'like'))
          } else {
            otherFilters.push(filtersRaw(key, data[key], '='))
          }
        }
      }
      this.otherFilters = otherFilters
      if (type !== 'export') {
        this.refreshTable()
      } else {
        return this.otherFilters
      }
    },
    // 刷新
    refreshTable(onPage) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(onPage)
      })
    },
    // 修改
    editHandle() {
      if (this.selectedList.length === 0) {
        this.$message.error('没有选中项！')
      } else if (this.selectedList.length > 1) {
        this.$message.error('只能选择一项！')
      } else {
        this.visibleEdit = true
      }
    },
    // 删除
    removeHandle() {
      if (!this.hasSelected) {
        this.$message.error('请选择要操作的数据！')
        return
      }
      return this.$msgbox({
        type: 'warning',
        title: '删除',
        message: '确认删除？',
        showCancelButton: true
      }).then(() => {
        return deleteBatch(this.selectedList.map(e => e.id)).then(res => {
          this.$message.success('删除成功！')
          this.refreshTable()
        })
      })
    },
    selectionChange(v) {
      this.selectedList = v
    },

    // 导入相关
    onChangeHandle(file, fileList) {
      this.fileList = fileList
    },
    removeFileHandle(file, fileList) {
      this.fileList = fileList.map((list) => {
        return list.raw
      }).filter(e => {
        return e !== undefined
      })
    },
    // 超出最大上传个数
    onExceed() {
      this.$message.info('每次最多只能导入一个文件')
    },
    // 导入
    onConfirmHandle(fileList) {
      if (fileList.length > 0) {
        const formData = new FormData()
        formData.append('file', fileList[0].raw)
        // 导入提示
        const loading = this.$loading({
          lock: true,
          text: '导入中，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        numberImport(formData).then(res => {
          this.$message.success('导入成功！')
          this.fileList = []
          this.$refs.export.cancelAllHandle()
          if (res.data instanceof Array && res.data.length > 0) {
            this.showErrMsg(res)
          } else {
            this.refreshTable()
          }
        }).catch(res => {
          this.showErrMsg(res)
        }).finally(() => {
          loading.close()
        })
      }
      //  else {
      //   this.$message.info('没有选择导入文件！')
      // }
    },
    // 显示错误
    showErrMsg(res) {
      const html = (res.data || []).sort((e1, e2) => {
        return e1.rowNum - e2.rowNum
      }).map(e => {
        return `<div>第${e.rowNum}行: ${e.errorMsg}</div>`
      })
      this.$message({
        title: '错误',
        dangerouslyUseHTMLString: true,
        showClose: true,
        duration: 0,
        message: `<div>${html.join('')}</div>`,
        type: 'error'
      })
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
  tr{
    background-color: white !important;
  }
}
</style>
